import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class ReservationService {
    private ReservationDao reservationDao = new ReservationDao();
    private Random random = new Random();

    // 生成指定时间的可用座位总数（1-10之间随机）
    private int getTotalSeats(Date time) {
        long seed = time.getTime();
        random.setSeed(seed);
        return random.nextInt(10) + 1;
    }

    // 显示指定时间的座位状态
    public void showSeats(Date time) throws SQLException {
        int totalSeats = getTotalSeats(time);
        List<Integer> reservedSeats = reservationDao.getReservedSeats(time);
        System.out.println("\n=== 座位状态（" + time + "）===");
        System.out.println("当前时间段总座位数：" + totalSeats);
        for (int i = 1; i <= totalSeats; i++) {
            String status = reservedSeats.contains(i) ? "已预约" : "空闲";
            System.out.println("座位" + i + "：" + status);
        }
    }

    // 预约座位（返回是否成功）
    public boolean reserveSeat(int studentId, int seatNo, Date time) throws SQLException {
        int totalSeats = getTotalSeats(time);
        if (seatNo < 1 || seatNo > totalSeats) {
            System.out.println("错误：座位号必须在1-" + totalSeats + "之间！");
            return false;
        }
        List<Integer> reservedSeats = reservationDao.getReservedSeats(time);
        if (reservedSeats.contains(seatNo)) {
            System.out.println("错误：座位" + seatNo + "已被预约！");
            return false;
        }
        reservationDao.reserve(studentId, seatNo, time);
        return true;
    }

    // 取消预约
    public void cancelReservation(int studentId, int seatNo, Date time) throws SQLException {
        reservationDao.cancel(studentId, seatNo, time);
    }

    // 查看我的预约记录
    public void showMyReservations(int studentId) throws SQLException {
        List<Reservation> reservations = reservationDao.getMyReservations(studentId);
        if (reservations.isEmpty()) {
            System.out.println("\n您暂无预约记录！");
            return;
        }
        System.out.println("\n=== 我的预约记录 ===");
        for (Reservation res : reservations) {
            System.out.println("座位" + res.getSeatNo() + "，时间：" + res.getReserveTime());
        }
    }

    // 供外部获取指定时间的总座位数
    public int getTotalSeatsForTime(Date time) {
        return getTotalSeats(time);
    }
}